package com.voxel.sense.infomsg.module.user.audit;

import android.text.TextUtils;

import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.ListUtil;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.ResourceUtils;
import com.example.com.common.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.RegionBean;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.utils.cover.BaseCoverStrategy;
import com.voxel.sense.infomsg.utils.cover.ConfigData2ConditionBeanCoverUtile;
import com.voxel.sense.infomsg.utils.manager.QueryConfigManager;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Condition;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.SearchMenuEntity;
import cyy.example.com.facotry.model.api.response.StaffDetailsEntity;
import cyy.example.com.facotry.model.api.response.UserRealNameAndIdEntity;
import cyy.example.com.facotry.net.RequestIdFactory;
import cyy.example.com.facotry.net.helper.NetHelper;

/**
 * @author ChenYiYao
 * @date 2018/5/14
 * des :
 */
public class AuditPresenter extends BasePresenter<AuditUserContract.View>
        implements AuditUserContract.Presenter, DataSource.Callback<BaseEntity> {


    private List mRoleDatas;
    private List mList;
    private String mRegionCode;

    public AuditPresenter(AuditUserContract.View view) {
        super(view);
    }

    @Override
    public void doLoadRoleData() {
        if (ListUtil.isEmpty(mRoleDatas)) {
            SearchMenuEntity roleType = QueryConfigManager.getInstance().getRoleType();
            BaseCoverStrategy strategy = new ConfigData2ConditionBeanCoverUtile();
            mRoleDatas = strategy.convertEntity(roleType, Constants.TYPE_USER_ROLE);
        }
        mView.onShowRoleView(mRoleDatas);
    }

    @Override
    public void doLoadUserType() {
        List mList = getUserTypeList();
        mView.onShowUserTypeView(mList,0);
    }

    private List getUserTypeList() {
        SearchMenuEntity departmentType = QueryConfigManager.getInstance().getDepartmentType();
        BaseCoverStrategy strategy = new ConfigData2ConditionBeanCoverUtile();
        return strategy.convertEntity(departmentType, Constants.TYPE_DEPARTMENT_TYPE);
    }

    @Override
    public void doLoadTeamDatas() {
        SearchMenuEntity squadronType = QueryConfigManager.getInstance().getSquadronType();
        BaseCoverStrategy strategy = new ConfigData2ConditionBeanCoverUtile();
        List mList = strategy.convertEntity(squadronType, Constants.TYPE_SQUADRON);
        mView.onShowTeamView(mList);
    }

    @Override
    public void doVarifyLeadInfo(String condition) {
        if (NetworkUtils.isConnected()) {
            mView.showLoading("");
            mView.onSetVarifyBtnEnable(false);
            NetHelper.getUserNameAndId(condition, this);
        } else {
            //网络不可用
            mView.showError(Factory.app().getResources().getString(R.string.network_error));
        }
    }

    @Override
    public void doLoadUserInfo(String id) {
        mView.showLoading("");
        NetHelper.searchStaffDetails(id, this);
    }

    @Override
    public void doAuditUser(String userId, String userName, String realName, String phone, String email, String roleId, String userType, String firm, String department, String LeadAccount, String LeadName, String LeadId, String job, String duty, String team) {
        if (TextUtils.isEmpty(roleId)) {
            //角色不能为空
            mView.showSnackBarWarning("请选择一个角色");
        } else if (!TextUtils.isEmpty(LeadAccount) && TextUtils.isEmpty(LeadName)) {
            //无法获取到上级用户
            mView.showSnackBarWarning("请填入正确上级账号，并校验");
        } else {
            mView.showLoading("");
            NetHelper.CheckUser(userId, userName, realName, mRegionCode, phone, email, roleId,
                    userType, firm, department, LeadAccount, LeadName, LeadId, job, duty, team, this);
        }

    }


    @Override
    public void onDataLoaded(BaseEntity data, int reqId) {
        if (mView == null) {
            return;
        }
        if (reqId == RequestIdFactory.QUERY_USER_DETAIL) {
            doUserInfoResponse(data);
        } else if (reqId == RequestIdFactory.USER_NAME_ID) {
            handleUserVarifyEvent(data, null);
        } else if (reqId == RequestIdFactory.CHECK_USER) {
            doCheckUserResponse(data, data.msg);
        }
    }

    private void doCheckUserResponse(BaseEntity data, String msg) {
        mView.dimissLoading();
        if (data != null && data.isSuccess()) {
            mView.onCheckUsdrSuccess();
        } else if (TextUtils.isEmpty(msg)) {
            mView.showError("审核失败，请重新审核");
        } else {
            mView.showError(msg);
        }
    }

    private void doUserInfoResponse(BaseEntity data) {
        StaffDetailsEntity staffEntity = (StaffDetailsEntity) data.getData();
        if (staffEntity != null) {
            String regionName = getRegionName(staffEntity.getRegionCode());
            mRegionCode = staffEntity.getRegionCode();

            //设置用户类型，默认为环保部门,环保部门code为1
            String userType = staffEntity.getUserType();
            userType = TextUtils.isEmpty(userType) ? "1" : userType;
            List<ConditionBean> userTypeList = getUserTypeList();
            int defaultIndex = 0;
            for (ConditionBean bean : userTypeList) {
                if (bean.getTipCode().equals(userType)) {
                    mView.onShowUserTypeView(userTypeList, defaultIndex);
                    break;
                }
                defaultIndex++;
            }

            //光明区才显示中队选项
            mView.onShowTeamItem("440000440300440310".equals(staffEntity.getRegionCode()));
            mView.onRefreshRegion(regionName);
        } else {
            //请求成功，没有拿到数据
            mView.showError(Factory.app().getString(R.string.data_rsp_error_unknown));
        }
        mView.dimissLoading();
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null) {
            return;
        }

        if (reqId == RequestIdFactory.USER_NAME_ID) {
            handleUserVarifyEvent(null, null);
        } else if (reqId == RequestIdFactory.CHECK_USER) {
            doCheckUserResponse(null, strRes);
        }

    }


    private void handleUserVarifyEvent(BaseEntity entity, String desc) {
        mView.dimissLoading();
        mView.onSetVarifyBtnEnable(true);
        if (entity != null && entity.isSuccess() && entity.getData() != null) {
            UserRealNameAndIdEntity data = (UserRealNameAndIdEntity) entity.getData();
            String realname = data.getRealname();
            String userId = data.getUserId();
            if (TextUtils.isEmpty(realname) || TextUtils.isEmpty(userId)) {
                mView.showSnackBarWarning("获取上级信息失败,请填入正确账号");
            } else {
                mView.onRefreshLeadName(realname, userId);
            }
        } else {
            mView.showSnackBarWarning("获取上级信息失败,请填入正确账号");
        }
    }


    private String getRegionName(String code) {
        String region = "";
        String s = ResourceUtils.readAssets2String("areaDataCode.json");
        Gson gson = new Gson();

        Type type = new TypeToken<List<RegionBean>>() {
        }.getType();
        List<RegionBean> mDatas = gson.fromJson(s, type);
        if (mDatas != null && mDatas.size() > 0) {
            for (RegionBean bean : mDatas) {
                //遍历省级数据
                if (code.equals(bean.getId())) {
                    region = bean.getName();
                    break;
                } else if (bean.getChild() != null && bean.getChild().size() > 0) {
                    for (RegionBean.ChildBeanX city : bean.getChild()) {
                        //遍历市级数据
                        if (code.equals(city.getId())) {
                            region = bean.getName() + " " + city.getName();
                            break;
                        } else if (city.getChild() != null && city.getChild().size() > 0) {
                            for (RegionBean.ChildBeanX.ChildBean districtBean : city.getChild()) {
                                //遍历区级数据
                                if (code.equals(districtBean.getId())) {
                                    region = city.getName() + " " + districtBean.getName();
                                }
                            }
                        }
                    }

                }
            }
        }
        return region;
    }
}
